<template>
  <div class="login-container">
    <div class="login-wrapper">
      <div class="welcome-section">
        <h1 class="welcome-title">欢迎回来</h1>
        <p class="welcome-subtitle">请登录您的账户以继续</p>
        <div class="brand-logo">
          <el-icon :size="42" color="#ffffff">
            <Grid />
          </el-icon>
          <span class="brand-name">系统管理平台</span>
        </div>
      </div>
      <div class="form-section">
        <LoginForm :pre-filled-account="preFilledAccount" @submit="handleLoginSubmit" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ElNotification, ElMessage } from 'element-plus'
  import LoginForm from '@/components/LoginForm.vue'
  import { login, validateToken, setAuthToken } from '@/api/userApi'
  import { Grid } from '@element-plus/icons-vue'
  import { onMounted } from 'vue'
  import { useRoute, useRouter } from 'vue-router'

  const router = useRouter()
  const route = useRoute()

  // 从路由参数中获取预填充的账号
  const preFilledAccount = ref<string>((route.query.account as string) || '')

  // 检查自动登录
  onMounted(async () => {
    console.log(
      '[onMounted] 当前account: ' +
        localStorage.getItem('account') +
        ' rememberMe: ' +
        localStorage.getItem('rememberMe')
    )

    // 同时检查 localStorage 和 sessionStorage
    const token = localStorage.getItem('token') || sessionStorage.getItem('token')
    const rememberMe = localStorage.getItem('rememberMe') === 'true'

    if (!token) {
      console.log('[onMounted] 没有token')
      return // 没有token直接返回
    }

    try {
      console.log('[onMounted] 当前token: ' + localStorage.getItem('token') + '\n开始验证token')
      // 调用后端接口验证token是否有效
      const result = await validateToken(token)

      if (result.valid) {
        console.log('[onMounted] token有效, 自动登录成功, 正在跳转...')
        // 如果token有效，跳转到首页
        ElMessage.success('自动登录成功, 正在跳转...')
        setTimeout(() => {
          router.push('/home')
        }, 2000)
      } else {
        console.log('[onMounted] token无效')
        // 如果token无效，清除存储并提示重新登录
        clearAllTokens()
        ElMessage.warning('您的会话已失效, 请重新登录')
      }
    } catch (error) {
      console.log('[onMounted] 验证token失败:', error)
      // 网络问题或token失效
      clearAllTokens()
      ElMessage.error('无法验证登录状态，请重新登录')
    }
  })

  // 清除所有存储的token
  const clearAllTokens = () => {
    localStorage.removeItem('token')
    localStorage.removeItem('rememberMe')
    localStorage.removeItem('account')
    localStorage.removeItem('username')
    sessionStorage.removeItem('token')
    sessionStorage.removeItem('username')
  }

  // 处理登录提交
  const handleLoginSubmit = async (loginData: { username: string; password: string; rememberMe: boolean }) => {
    try {
      // 发送登录请求
      const userResponse = await login(loginData.username, loginData.password)
      const token = userResponse.token

      // 设置全局Token
      setAuthToken(token)

      // 根据rememberMe选择存储位置
      if (loginData.rememberMe) {
        localStorage.setItem('token', token)
        localStorage.setItem('rememberMe', 'true')
        localStorage.setItem('account', loginData.username)
        localStorage.setItem('username', userResponse.username)
      } else {
        sessionStorage.setItem('token', token)
        sessionStorage.setItem('username', userResponse.username)
        localStorage.removeItem('rememberMe')
        localStorage.removeItem('account')
        localStorage.removeItem('username')
      }

      // 登录成功提示
      ElNotification.success({
        title: '登录成功',
        message: `欢迎回来，${userResponse.username}！`,
        duration: 3000,
      })

      // 跳转到首页
      router.push('/home')
      console.log('进入首页')
    } catch (error) {
      let errorMessage = '登录失败，请稍后再试'

      if (error instanceof Error) {
        if (error.message.includes('401') || error.message.includes('密码错误')) {
          errorMessage = '用户名或密码错误'
        } else if (error.message.includes('network')) {
          errorMessage = '网络异常，请检查连接'
        } else {
          errorMessage = error.message
        }
      }

      ElMessage.error({
        message: errorMessage,
        duration: 3000,
        showClose: true,
      })
    }
  }
</script>

<style scoped>
  .login-container {
    height: 100vh;
    background-color: #f0f8ff;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .login-wrapper {
    background-color: white;
    border-radius: 16px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    display: flex;
    width: 90%;
    max-width: 1200px;
    min-height: 650px;
    overflow: hidden;
  }

  .welcome-section {
    flex: 1;
    padding: 80px 20px 80px 60px;
    background: linear-gradient(135deg, #1e90ff 0%, #74b9ff 100%);
    color: white;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .welcome-title {
    font-size: 2.5rem;
    margin-bottom: 20px;
    font-weight: 700;
  }

  .welcome-subtitle {
    font-size: 1.2rem;
    opacity: 0.9;
    margin-bottom: 40px;
  }

  .brand-logo {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-top: 60px;
  }

  .brand-name {
    font-size: 1.8rem;
    font-weight: 700;
  }

  .form-section {
    flex: 1.5;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  @media (max-width: 768px) {
    .login-wrapper {
      flex-direction: column;
    }

    .welcome-section {
      padding: 40px 20px;
      text-align: center;
    }

    .brand-logo {
      justify-content: center;
    }
  }
</style>
